
// 递归函数处理传入层级树形控件的函数
export function recursionTree (list, map) {
  const result = []
  // 遍历 list
  list.forEach((item) => {
    // 读取 map 的键值映射
    const id = item[map.id]
    const code = item[map.code]
    const label = item[map.label]
    let children = item[map.children]

    // 如果有子节点，递归
    if (children) {
      children = recursionTree(children, map)
    }
    result.push({
      id,
      code,
      label,
      children
    })
  })
  return result
}

// 扁平化 数组
export function deepFlatten (arr, map) {
  const result = []
  // 遍历 list
  arr.forEach((item) => {
    // 读取 map 的键值映射
    let children = item[map.children]

    // 如果有子节点，递归
    if (children) {
      children = recursionTree(children, map)
    }
    result.push({
      children
    })
  })
  return result
}

/**
 * 按数组对象的某一个属性排序
 * params: arr 数组
 * params: property 对象属性
 * params: desc 排序方式
 */
export const sortBy = (arr = [], property, desc = false) => {
  return arr.sort((obj1, obj2) => {
    if (desc) {
      return obj2[property] - obj1[property]
    }
    return obj1[property] - obj2[property]
  })
}

/**
 * 处理级联选择器的数据
 * @param list
 * @param map
 * @returns {Array}
 */
export const recursion = (list, map) => {
  const result = []
  list.forEach((item) => {
    const value = item[ map.value ] && item[ map.value ].toString()
    const label = item[ map.label ]
    let children = item[ map.children ]
    let selected = false
    if (children) {
      children = recursion(children, map)
    }
    value && label && result.push({
      value,
      label,
      children,
      selected
    })
  })
  return result
}

/**
 * 把多级结构打成一个Map
 * @param list
 * @param property
 * @param children
 * @param result
 * @returns {Map<any, any>}
 */
export const recursionToMap = (list, property, children, result = new Map()) => {
  list.forEach((item) => {
    if (item[children]) {
      result = recursionToMap(item[children], property, children, result)
    }
    result.set(item[property], item)
  })
  return result
}

// 根据末级部门code找出完整code数组路径（应付级联）
export function findTeamCodePath (teamList, saleTeamCode) {
  const container = []
  function di (items, targetCode, container) {
    const result = items.find(item => {
      if (item.value === targetCode) return true
      const { children = [] } = item
      if (children.length) return di(children, targetCode, container)
    })
    if (result) container.unshift(result.value)
    return result
  }
  di(teamList, saleTeamCode, container)
  return container
}
